package ch5.part7;

import java.util.Stack;

/**
 * 使用栈实现队列的出队和入队
 * 出入队平均时间复杂度：O(n) = 1
 *
 * @author liuwanxiang
 * @version 2019/06/17
 */
public class StackQueue {

    private Stack<Integer> stackA = new Stack<>();
    private Stack<Integer> stackB = new Stack<>();

    private void in(Integer data) {
        stackA.push(data);
    }

    private Integer out() {
        if (stackB.empty()) {
            if (stackA.empty()) {
                return null;
            }
            transfer();
        }
        return stackB.pop();
    }

    private void transfer() {
        while (!stackA.empty()) {
            stackB.push(stackA.pop());
        }
    }

    public static void main(String[] args) {

        StackQueue queue = new StackQueue();
        queue.in(1);
        queue.in(2);
        queue.in(3);
        System.out.println(queue.out());
        System.out.println(queue.out());
        queue.in(4);
        System.out.println(queue.out());
        System.out.println(queue.out());

    }
}
